<template>
  <div class="ai-plan-container">
    <!-- 页面标题 -->
    <el-page-header :icon="null" title="智能行程规划" class="page-header">
      <template #content>
        <div class="header-content">
          <el-icon class="header-icon"><MagicStick /></el-icon>
          <h1 class="header-title">AI行程生成</h1>
        </div>
      </template>
    </el-page-header>

    <!-- 主内容卡片 -->
    <el-card shadow="hover" class="main-card">
      <!-- 表单部分 -->
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-position="top"
          @submit.prevent="handleSubmit"
      >
        <el-row :gutter="30">
          <!-- 左栏 -->
          <el-col :span="12">
            <el-form-item label="兴趣标签：" prop="interestTags">
              <el-select
                  v-model="formData.interestTags"
                  multiple
                  filterable
                  allow-create
                  placeholder="请选择或输入兴趣标签"
                  class="full-width"
              >
                <el-option
                    v-for="tag in presetTags"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="预算范围（元）：" prop="budgetRange">
              <el-slider
                  v-model="budgetRange"
                  range
                  :min="500"
                  :max="10000"
                  :step="500"
                  @change="updateBudgetText"
              />
              <div class="budget-display">
                {{ formData.budgetRange }}
              </div>
            </el-form-item>
          </el-col>

          <!-- 右栏 -->
          <el-col :span="12">
            <el-form-item label="行程天数：" prop="durationDays">
              <el-input-number
                  v-model="formData.durationDays"
                  :min="1"
                  :max="30"
                  controls-position="right"
                  class="full-width"
              />
            </el-form-item>

            <el-form-item label="时间偏好：" prop="timePreference">
              <el-radio-group v-model="formData.timePreference">
                <el-radio-button label="morning">上午为主</el-radio-button>
                <el-radio-button label="afternoon">下午为主</el-radio-button>
                <el-radio-button label="fullDay">全天安排</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 提交按钮 -->
        <div class="submit-area">
          <el-button
              type="primary"
              :loading="loading"
              native-type="submit"
              class="submit-btn"
          >
            <template #icon>
              <el-icon><MagicStick /></el-icon>
            </template>
            生成智能行程
          </el-button>
        </div>
      </el-form>

      <!-- 加载状态 -->
      <el-skeleton :rows="6" animated v-if="loading" />

      <!-- 结果展示 -->
      <div v-if="resultData" class="result-container">
        <div class="summary-section">
          <h2 class="summary-title">
            为您生成 {{ resultData.durationDays }} 天行程
            <el-tag type="success" class="budget-tag">
              总预算: {{ resultData.totalBudget }}
            </el-tag>
          </h2>
        </div>

        <el-collapse v-model="activeDay" accordion class="day-collapse">
          <el-collapse-item
              v-for="day in resultData.dailyPlans"
              :key="day.dayNumber"
              :name="day.dayNumber"
              :title="`第 ${day.dayNumber} 天行程`"
          >
            <div class="day-plan">
              <el-timeline>
                <el-timeline-item
                    v-for="(spot, index) in day.spots"
                    :key="index"
                    :timestamp="spot.time"
                    placement="top"
                >
                  <el-card shadow="hover">
                    <h3>{{ spot.name }}</h3>
                    <p class="spot-info">
                      <el-icon><Location /></el-icon>
                      {{ spot.location }}
                      <el-divider direction="vertical" />
                      <el-icon><Clock /></el-icon>
                      建议时长: {{ spot.duration }}
                    </p>
                    <!-- 添加价格显示 -->
                    <el-tag type="success" class="price-tag">
                      ￥{{ spot.price }}
                    </el-tag>
                  </el-card>
                </el-timeline-item>
              </el-timeline>

              <div class="day-summary">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="当日住宿">
                    <el-tag type="info">
                      {{ day.hotel.name }} (¥{{ day.hotel.price }})
                    </el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="交通方式">
                    <el-tag type="warning">
                      {{ day.transport.type }} (¥{{ day.transport.price }})
                    </el-tag>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
  </div>
</template>

<script setup>

import { ref, reactive } from 'vue'
import { MagicStick, Location, Clock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const formRef = ref()
const loading = ref(false)
const activeDay = ref(1)
const budgetRange = ref([1000, 3000])
const resultData = ref(null)

const formData = reactive({
  interestTags: [],
  budgetRange: '1000-3000',
  durationDays: 3,
  timePreference: 'fullDay'
})

const presetTags = [
  '自然风光', '历史人文', '美食体验',
  '亲子游乐', '户外运动', '城市观光'
]

const formRules = {
  interestTags: [
    { required: true, message: '请至少选择一个兴趣标签', trigger: 'change' }
  ],
  durationDays: [
    { required: true, message: '请输入行程天数', trigger: 'blur' }
  ]
}

function updateBudgetText(value) {
  formData.budgetRange = `${value[0]}-${value[1]}`
}

async function handleSubmit() {
  try {
    await formRef.value.validate()
    loading.value = true

    // 构造请求参数
    const requestData = {
      interestTags: formData.interestTags.join(','),
      budgetRange: formData.budgetRange,
      durationDays: formData.durationDays,
      timePreference: formData.timePreference,
      userId: 2 // 根据实际用户系统获取
    }

    // 调用后端API
    const response = await axios.post(BASE_URL+'/itineraries/generate', requestData)

    // 转换数据结构适配前端
    resultData.value = {
      durationDays: response.data.data.durationDays,
      totalBudget: response.data.data.totalBudget,
      dailyPlans: response.data.data.dailyPlans.map(plan => ({
        dayNumber: plan.dayNumber,
        spots: plan.spots.map(spot => ({
          name: spot.name,
          location: spot.location,
          time: plan.timeRange.split('-')[0], // 取开始时间
          duration: '2小时' // 根据业务逻辑计算
        })),
        hotel: {
          name: plan.hotelName,
          price: plan.hotelPrice
        },
        transport: {
          type: plan.transportInfo.split(' ')[0],
          price: plan.transportPrice
        }
      }))
    }

    ElMessage.success('行程生成成功！')
  } catch (error) {
    ElMessage.error(error.message || '生成失败，请检查输入')
  } finally {
    loading.value = false
  }
}

function generateMockData() {
  return Array.from({ length: formData.durationDays }, (_, i) => ({
    dayNumber: i + 1,
    spots: [
      {
        name: `景点 ${i + 1}-1`,
        location: '景点地址',
        time: '09:00',
        duration: '2小时'
      },
      {
        name: `景点 ${i + 1}-2`,
        location: '景点地址',
        time: '14:00',
        duration: '3小时'
      }
    ],
    hotel: {
      name: `酒店 ${i + 1}`,
      price: (500 + i * 100).toFixed(0)
    },
    transport: {
      type: ['大巴', '高铁', '飞机'][i % 3],
      price: (300 + i * 50).toFixed(0)
    }
  }))
}
</script>

<style scoped>
.ai-plan-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-icon {
  font-size: 28px;
  color: var(--el-color-primary);
}

.header-title {
  margin: 0;
  font-size: 24px;
}

.main-card {
  margin-top: 20px;
}

.full-width {
  width: 100%;
}

.budget-display {
  margin-top: 8px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.submit-area {
  margin-top: 30px;
  text-align: center;
}

.submit-btn {
  padding: 15px 40px;
  font-size: 16px;
}

.result-container {
  margin-top: 30px;
}

.summary-title {
  display: flex;
  align-items: center;
  gap: 20px;
}

.day-plan {
  padding: 20px;
}

.spot-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.day-summary {
  margin-top: 20px;
}

:deep(.el-collapse-item__header) {
  font-weight: bold;
  font-size: 16px;
}

.budget-tag {
  margin-left: 10px;
  font-size: 16px;
  height: 32px;
  line-height: 32px;
}
</style>